import java.util.concurrent.atomic.AtomicInteger;

public class SyncThread implements Runnable {
	private static final int TOT = 5, MAX = 50;
	private int ind;
	private AtomicInteger i;
	public SyncThread(int ind, AtomicInteger i) {
		this.ind = ind;
		this.i = i;
	}
	
	public static void main(String[] args) {
		AtomicInteger i = new AtomicInteger();
		for(int j = 0; j < TOT; j++)
			new Thread(new SyncThread(j, i)).start();
	}

	@Override
	public void run() {
		int max = TOT * (MAX / TOT);
		max = max + ind < MAX ? max + ind : max - TOT + ind;
		synchronized(i) {
			while(i.get() <= max) {
				while(i.get() % TOT != ind) {
					try {
						i.wait();
					} catch(Exception e) {
						System.out.println(e.getMessage());
					}
				}
				System.out.println(ind + ": " + i.get());
				i.incrementAndGet();
				i.notifyAll();
			}
		}
	}
}
